import React from 'react';
import {connect} from 'react-redux';
import {messages} from "share/common";
import menuRoute from 'routes/menuRoute';
import FileSaver from "file-saver";
import chooserData from 'share/chooserData';
import SlideFrame from 'components/slide-frame';
import ListSelector from 'components/list-selector';
import ImportErrInfo from 'components/template/import-err-info';
import ExportModal from 'components/template/export-modal/export-modal';
import 'styles/setting/cost-center-group/cost-center-group-detail.scss';
import EditCostCenterGroup from "containers/setting/cost-center-group/edit-cost-center-group";
import costCenterGroupService from 'containers/setting/cost-center-group/cost-center-group.service';
import {Button, Table, Col, Row, Divider, Menu, Dropdown, Icon, Badge, Modal, message, Tooltip, Upload, Popover} from 'antd';
import 'styles/components/template/import-modal/import-modal.scss'
import ResizeTable from "components/resize-table";

class CostCenterGroupDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {

      showImportBankModelForPerson: false,
      showImportErrInfoForPerson: false,

      progressImportErrInfo: 1,
      transactionOID: null,
      errorsList: [],
      fileList: [],
      fileUploading: false,//文件是否正在上传

      id: this.props.location.state.id,
      code: this.props.location.state.costCenterGroupCode,
      record: {},
      extraParams: {},
      selectorItem: chooserData['add_cost_center_group'],
      visible: false,
      loading: false,
      data: [],
      page: 0,
      pagination: {
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      columns: [
        {
          title: messages('setting.key373'/*成本中心*/),
          dataIndex: 'costCenterName',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>

        },
        {
          title: messages('setting.key374'/*成本中心项*/),
          dataIndex: 'costCenterItemName',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>

        },
        {
          title: messages('common.column.status'/*状态*/),
          dataIndex: 'enabled', render: (text) => {
          return <span><Badge status={text ? "success" : 'error'}/>
            {text ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}
                   </span>
        }
        },
        {
          title: messages('common.operation')/*操作*/,
          dataIndex: 'operation', render: (text, record) => {
          return <a onClick={(e) => {
            this.onRecordDelete(e, text, record)
          }} style={{fontSize: 13}}>{messages('common.delete')/* 删除 */}</a>
        }
        },
      ],
      editVisible: false,
      selectedRowKeys: [],
      downloading: false,
      costCenterGroupDefine: menuRoute.getRouteItem('cost-center-group-define', 'key').url
    }
  };

  componentWillMount() {
    this.getCostCenterGroupDetail();
    this.getTableData();
  };

  //获取成本中心的详情信息
  getCostCenterGroupDetail = () => {
    const {id, page} = this.state;
    this.setState({
      loading: true,
    });
    costCenterGroupService.getCostCenterGroupDetail(id, page).then(res => {
      let record = res.data;
      this.setState({
        record,
        loading: false,
        extraParams: {
          costCenterId: record.costCenterId,
          setOfBooksId: record.setOfBooksId,
          costCenterGroupId: record.id,
        },
      });
    }).catch(res => {
      this.setState({
        loading: false,
      });
    });
  };

  //获取列表数据
  getTableData = () => {
    const {id, page} = this.state;
    this.setState({
      loading: true,
    });
    costCenterGroupService.getCostCenterList(id, page).then(res => {
      this.setState({
        data: res.data,
        pagination: {
          total: Number(res.headers['x-total-count']) || 0,
          onChange: this.onPageChange,
          current: this.state.page + 1,
        },
        loading: false,
      });
    }).catch(res => {
      this.setState({
        loading: false,
      });
    });
  };

  //点击分页
  onPageChange = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({
        page: page - 1,
      }, () => {
        this.getTableData();
      });
    }
  };

  //点击编辑
  onEdit = () => {
    this.showSlide(true);
  };

  //删除某一行
  onRecordDelete = (e, text, record) => {
    costCenterGroupService.operateCostCenterList([record.id], 'DELETED').then(res => {
      this.getTableData();
    })
  };

  //点击模态框的确定
  handleModalOK = (res) => {
    this.setState({
      loading: true,
    });
    //未全选
    let params = {
      selectedAll: false,
      selectedCostCenterGroupAssigns: res.result,
    };
    costCenterGroupService.addCostCenterList(params).then(res => {
      this.getTableData();
      this.setState({
        visible: false,
        loading: false,
      });
    }).catch(err => {
      this.setState({
        loading: false,
      });
    });

  };

  //点击模态框的取消
  handleModalCancel = () => {
    this.setState({
      visible: false,
    });
  };

  //点击手工新建
  handleMenuClick = (e) => {
    if (e.key === messages('setting.key375'/*手工新建*/)) {
      this.setState({
        visible: true,
      });
    } else {
      this.handleImportShowForPerson();
    }
  };

  handleImportShowForPerson = () => {
    this.setState({
      showImportBankModelForPerson: true
    });
  };

  cancelImportForPerson = () => {
    this.setState({
      showImportBankModelForPerson: false
    });
  };

  //人员导入的错误信息-start
  showImportErrInfoForPerson = () => {
    this.setState({
      showImportErrInfoForPerson: true
    });
  };

  hideImportErrInfoForPerson = () => {
    this.setState({
      showImportErrInfoForPerson: false
    });
    this.getTableData();
  };


  //人员导入的错误信息-end
  handleFileUploadForPerson = () => {
    const {fileList, extraParams} = this.state;
    const formData = new FormData();
    formData.append('file', fileList[0]);
    formData.append('setOfBooksId', extraParams.setOfBooksId);
    formData.append('costCenterGroupId', extraParams.costCenterGroupId);
    this.setState({
      uploading: true,
      fileUploading: true,
    });
    costCenterGroupService.importTemplateCostCenterPersonOID(formData)
      .then((res) => {
        this.setState({
          fileList: [],
          uploading: false,
          fileUploading: false,
          showImportBankModelForPerson: false,
          transactionOID: res.data.transactionOID//这个transactionOID在导出错误信息的时候，需要用到
        }, () => {
          this.showImportErrInfoForPerson();
          this.showTransactionLogDialog(this.state.transactionOID);   // 将参数传给dialog
        });
      })
      .catch((res) => {
        this.setState({
          uploading: false,
          fileUploading: false,
        });
      });
  };

  //导入时错误信息
  showTransactionLogDialog = (transactionOID) => {
    costCenterGroupService.getCostCenterBatchTransactionLog(transactionOID)
      .then((res) => {
        let data = res.data;
        if (data.totalEntities === 0) {
          this.hideImportErrInfoForPerson();
          return;
        } else {
          let errors = data.errors;
          let errorsList = this.getErrorDataByerrors(errors);
          let progressImportErrInfo = this.getProgressByData(data);
          this.setState({
            progressImportErrInfo,
            errorsList
          });
          if ((data.successEntities + data.failureEntities) !== data.totalEntities) {
            let gapTime = 500;
            setTimeout(() => {
              //请求频率涉及到一个算法
              this.showTransactionLogDialog(this.state.transactionOID);   // 将参数传给dialog
            }, gapTime)
          } else {
            //导入完成了
            if (JSON.stringify(res.data.errors) === '{}') {
              message.success(messages("common.operate.success"));
              this.hideImportErrInfoForPerson();
              this.getTableData();
            }
          }
        }
      })
  };


  hideImportErrInfo = () => {
    this.setState({
      showImportErrInfo: false
    });
  };

  //获取百分进度
  getProgressByData = (data) => {
    return Math.round((data.failureEntities + data.successEntities) * 100 / data.totalEntities);
  };

//通过错误信息，解析成表格
  getErrorDataByerrors = (errs) => {
    let data = [];
    for (let key in errs) {
      let row = {};
      row.line = errs[key];
      if (row.line.length > 1) {
        let _line = [];
        for (let i = 0; i < row.line.length; i++) {
          _line.push(row.line[i]);
          if (i < row.line.length - 1) {
            _line.push(",");
          }
        }
        row.line = _line;
      }
      row.msg = key;
      data.push(row);
    }
    return data;
  };

  //下载模板：成本中心项
  downloadTemplatePerson = () => {
    this.setState({
      downloading: true,
    });
    costCenterGroupService.downloadCostCenterItemPersonTemplate()
      .then((res) => {
        let b = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        // 成本中心组模板
        let name = messages('setting.key376'/*成本中心组模板*/);
        FileSaver.saveAs(b, `${name}.xlsx`);
        this.setState({
          downloading: false,
        });
      })
      .catch((res) => {
        this.setState({
          downloading: false,
        });
      });
  };

  //成本中心项-人员导出错误信息
  exportFailedLogForPerson = () => {
    costCenterGroupService.exportCostCenterPersonBatchTransactionLog(this.state.transactionOID)
      .then((res) => {
        let b = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        // 成本中心项-导出错误信息
        let name = messages('setting.key377'/*成本中心项-导出错误信息*/);
        FileSaver.saveAs(b, `${name}.xlsx`);
      })
      .catch((res) => {
      });
  };

  //侧滑关闭后
  afterCloseSlide = () => {
    this.getCostCenterGroupDetail();
    this.showSlide(false);
  };

  //show侧滑
  showSlide = (flag) => {
    this.setState({
      editVisible: flag,
    });
  };

  //列表选择更改
  onSelectChange = (selectedRowKeys) => {
    this.setState({selectedRowKeys})
  };

  //批量删除成本中心项
  batchDelete = () => {
    const {selectedRowKeys} = this.state;
    costCenterGroupService.operateCostCenterList(selectedRowKeys, 'DELETED').then(res => {
      this.getTableData();
      this.setState({
        selectedRowKeys: [],
      })
    })
  };


  render() {
    const {data, columns, loading, pagination, costCenterGroupDefine, visible, extraParams, record,
      selectorItem, editVisible, selectedRowKeys, fileList, downloading, fileUploading,
      showImportErrInfoForPerson, progressImportErrInfo, errorsList, showImportBankModelForPerson, id} = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const props = {
      onRemove: (file) => {
        this.setState(({fileList}) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        if (file.name.endsWith('.xls') || file.name.endsWith('.xlsx')) {
          this.setState(({fileList}) => ({
            fileList: [file],
          }));
          return false;
        } else {
          message.error(messages('setting.key378'/*请上传Excel文件*/))
          return false;
        }
      },
      fileList: fileList,
    };
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        <Menu.Item key={messages('setting.key375'/*手工新建*/)}>{messages('setting.key375'/*手工新建*/)}</Menu.Item>
        <Menu.Item key={messages('common.import')/* 导入 */}>{messages('common.import')/* 导入 */}</Menu.Item>
      </Menu>
    );
    return (
      <div className={'cost-center-group-detail'}>
        <h3>{messages('setting.key379'/*成本中心组详情*/)}</h3>{/*成本中心组详情*/}
        <div style={{padding: 15}} className='cost-center-group-detail-info'>
          <Row>
            <Col span={2}>{messages('common.baseInfo')}</Col>{/*基本信息*/}
            <Col span={6}>
              <a onClick={this.onEdit} style={{fontSize: 13}}>{messages('common.edit')}</a>{/*编辑*/}
            </Col>
          </Row>
          <Divider/>
          <Row>
            <Col span={7}>
              <div style={{textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden'}}>
                {messages('setting.key369'/*成本中心组代码*/)}：
                <Tooltip title={record.costCenterGroupCode}
                         style={{width: '100%'}}
                         placement={'topLeft'}
                         getPopupContainer={triggerNode => triggerNode.parentNode}>{record.costCenterGroupCode}
                </Tooltip>
              </div>
            </Col>
            <Col span={8} offset={1}>
              <div style={{textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden'}}>
                {messages('setting.key370'/*成本中心组名称*/)}：
                <Tooltip title={record.costCenterGroupName}
                         style={{width: '100%'}}
                         placement={'topLeft'}
                         getPopupContainer={triggerNode => triggerNode.parentNode}>
                  {record.costCenterGroupName}
                </Tooltip>
              </div>
            </Col>
            <Col span={8}>{messages('common.column.status'/*状态*/)}：
              {<span><Badge status={record.enabled ? "success" : 'error'}/>
                {record.enabled ? messages("common.status.enable")/*启用？*/ : messages('common.status.disable')/*禁用*/}
               </span>
              }
            </Col>
          </Row>
          <Row style={{marginTop: 10}}>
            <Col span={16}>
              <div style={{textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden'}}>
                {messages('setting.key186'/*描述*/)}：
                <Tooltip title={record.description}
                         style={{width: '100%'}}
                         placement={'topLeft'}
                         getPopupContainer={triggerNode => triggerNode.parentNode}>
                  {record.description}
                </Tooltip>
              </div>
            </Col>
          </Row>
        </div>
        <br/>
        <div>
          <Dropdown overlay={menu}>
            <Button type={'primary'}>
              {messages('setting.key381'/*新建值内容*/)} <Icon type="down"/>
            </Button>
          </Dropdown>
          <div style={{marginLeft: 15, display: 'inline-block'}}>
            <ExportModal
              type={"btn"}
              codeCheck={true}
              disabled={!data.length}
              exportTitle={messages('setting.key382'/*导出数据*/)}
              exportType="COST_CENTER_GROUP_ASSIGN"
              exportCondition={{"costCenterGroupId": id,}}
              exportCommand={"COST_CENTER_GROUP_ASSIGN"}/>
          </div>
          <Button style={{marginLeft: 15}}
                  disabled={!selectedRowKeys.length}
                  onClick={this.batchDelete}>{messages('common.delete')/* 删除 */}</Button>
        </div>
        <div style={{marginTop: 10, marginBottom: 10}}>
          {messages('common.total', {total: `${pagination.total}`})}
          {/*共搜索到{pagination.total}条数据*/}
        </div>
        <div className={"cost-center-group-detail-table"}>
          <ResizeTable
            bordered
            size={'middle'}
            rowKey={'id'}
            dataSource={data}
            columns={columns}
            loading={loading}
            pagination={pagination}
            rowSelection={rowSelection}
          />
        </div>
        <div style={{marginTop: 20, marginBottom: 20}}>
          <a onClick={() => {
            this.context.router.push(costCenterGroupDefine)
          }} style={{fontSize: 13}}>{messages('common.back')/*返回*/}</a>
        </div>
        <div className={"cost-center-group-detail-ListSelector"}>
          <ListSelector type='add_cost_center_group'
                        visible={visible}
                        extraParams={extraParams}
                        selectorItem={selectorItem}
                        onOk={this.handleModalOK}
                        confirmLoading={loading}
                        onCancel={() => this.handleModalCancel()}
                        clearText={messages("common.reset")}/>
          {/*成本中心项-人员*/}
        </div>
        <div>
          {JSON.stringify(record) !== '{}' &&
          <SlideFrame title={messages('setting.key383'/*编辑成本中心组*/)}
                      show={editVisible}
                      content={EditCostCenterGroup}
                      afterClose={this.afterCloseSlide}
                      onClose={() => this.showSlide(false)}
                      params={{record: record, show: editVisible}}/>
          }
        </div>
        <Modal closable
               className="import-modal"
               title={messages('setting.key304'/*导入*/)}//导入
               visible={showImportBankModelForPerson}
               onCancel={this.cancelImportForPerson}
               destroyOnClose={true}
               footer={null}>


          <div>
            <div className={"bottom-class"}><h4>{messages('setting.key384'/*创建模板*/)}</h4></div>
            <div className={"bottom-left-class"}>
              <div className={"bottom-class top-class"}>
                <Button icon="download"
                        loading={downloading}
                        onClick={this.downloadTemplatePerson}>
                  {/*下载模板*/}
                  {messages('setting.key385')}
                </Button>
              </div>
              <div className={"bottom-class top-class"}>1.{messages('setting.key1746')/*点击【下载模板】按钮*/}</div>
              <div className={"bottom-class"}>2.{messages('setting.key387'/*严格按照导入模板整理数据，检查必输事项是否缺少数据*/)}</div>
              <div className={"bottom-class"}>{messages('setting.key388'/*3.关闭Excel文件后，方可进行数据导入*/)}</div>
            </div>
            <div><h4>{/*上传模板*/}{messages('setting.key308'/*上传模板*/)}</h4></div>
            <div className={"bottom-left-class top-class"}>
              <div className={"bottom-class top-class"}>
                1.{messages('setting.key1748')/*点击【选择一个文件】按钮，选择更新过的模板文件，并点击确定*/}
              </div>
              <div className={"bottom-class"}>2.{messages('setting.key1752')/*点击【开始上传】按钮*/}</div>
              <div className={"top-class"}>
                <div className={"inline-div right-class"}>
                  <Upload {...props}>
                    <Button>
                      {/*选择一个文件*/}
                      {messages('setting.key309'/*选择一个文件*/)}
                    </Button>
                  </Upload>
                </div>
                <div className={"inline-div"}>
                  <Button
                    className="upload-file-start"
                    type="primary"
                    onClick={this.handleFileUploadForPerson}
                    disabled={fileList.length === 0}
                    loading={fileUploading}>
                    <Icon type="upload"/>
                    {/*?上传中:开始上传*/}
                    {fileUploading ? messages('setting.key310'/*上传中*/) : messages('setting.key311'/*开始上传*/)}
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </Modal>
        {/*成本中心项-人员*/}
        <ImportErrInfo
          progress={progressImportErrInfo}
          cancel={this.hideImportErrInfoForPerson}
          exportErrInfo={this.exportFailedLogForPerson}
          errorsList={errorsList}
          visible={showImportErrInfoForPerson}/>
      </div>
    )
  }

}

CostCenterGroupDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {}
}

export default connect(mapStateToProps)(CostCenterGroupDetail);
